#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main(void)
{
    int fd = open("./01_fdopen.c", O_RDONLY);
    if (fd < 0)
    {
        perror("open");
        exit(-1);
    }

    FILE* pFile = fdopen(fd, "r");
    if (NULL == pFile)
    {
        perror("fopen");
        exit(-1);
    }

    //read influences fread, fread doesn't influence read
    char buf[16] = {0};
    read(fd, buf, 4);
    printf("read: %s\n", buf);
    fread(buf, 1, 4, pFile);
    printf("fread: %s\n", buf);
    read(fd, buf, 4);
    printf("read2: %s\n", buf);
    fread(buf, 1, 4, pFile);
    printf("fread2: %s\n", buf);

    //fclose also closes associated fd
    fclose(pFile);

    FILE* pFile2 = fdopen(fd, "r");
    if (NULL == pFile2)
    {
        perror("fopen");
    }
    else
    {
        fclose(pFile2);
    }

    return 0;
}